import { Form, message } from 'antd';
import { useEffect } from 'react';

import { useRequest, useSetState } from 'ahooks';

import { postRoleCreate, postRoleInfo, postRoleUpdate } from '@/services/systemManagement/role';

import useMenuTree from './useMenuTree';

import type { IRoleInfo, IRoleList } from '@/types/systemManagement/role';
import { ERoleStatus } from '@/types/systemManagement/role';

export default () => {
  const { appCode = '' } = {}

  const [editForm] = Form.useForm();
  const menuTreeHooks = useMenuTree();
  const { setCheckedKeys, defaultPageList } = menuTreeHooks;

  // 保存
  const saveReq = useRequest(postRoleCreate, {
    manual: true,
  });
  // 更新
  const updateReq = useRequest(postRoleUpdate, {
    manual: true,
  });

  const [modal, setModal] = useSetState<{
    open: boolean;
    type?: 'add' | 'edit' | 'detail';
    loading: boolean;
    data: IRoleInfo | null;
  }>({
    open: false,
    loading: true,
    data: null,
  });
  // 关闭编辑or新增框
  function onClose() {
    setModal({
      open: false,
      data: null,
    });
    editForm.resetFields();
  }
  // 打开编辑or新增框
  async function onOpen(data: IRoleList | null, type: 'add' | 'edit' | 'detail') {
    if (type !== 'add' && data) {
      setModal({
        open: true,
        type,
        loading: true,
      });
      const res = await postRoleInfo({
        id: data.id,
      });
      if (res.success) {
        setModal({
          loading: false,
          data: res.data,
        });
        setCheckedKeys(res.data?.permissionList || []);
        editForm.setFieldsValue({
          ...res.data,
          status: res.data.status === 0,
          // roleCode: res.data?.roleCode,
        });
      } else {
        setModal({
          loading: false,
        });
      }
    } else {
      setModal({
        open: true,
        loading: false,
        type,
      });
      setCheckedKeys([]);
    }
  }

  //提交
  async function onSubmit() {
    const values = await editForm.validateFields();
    const formatValues = {
      ...values,
      status: values.status ? ERoleStatus.ENABLED : ERoleStatus.DISABLED,
    };
    if (modal.type === 'edit') {
      const res = await updateReq.runAsync({
        ...formatValues,
        id: modal.data?.id,
      });
      if (res.success) {
        onClose();
        message.success('保存成功！');
      }
    } else if (modal.type === 'add') {
      const res = await saveReq.runAsync({ ...formatValues });
      if (res.success) {
        onClose();
        message.success('新增角色成功！');
      }
    }
  }

  useEffect(() => {
    const defaultUrlMenuId = editForm.getFieldValue('defaultUrlMenuId');
    if (!defaultUrlMenuId) {
      return;
    }
    if (defaultPageList.filter((item) => String(item.id) === String(defaultUrlMenuId)).length < 1) {
      editForm.resetFields(['defaultUrlMenuId']);
    }
  }, [defaultPageList]);

  return {
    modal,
    onOpen,
    onClose,
    editForm,
    onSubmit,
    submitLoading: updateReq.loading || saveReq.loading,
    menuTreeHooks,
  };
};
